package com.dempsey.good.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dempsey.api.model.LoginUser;
import com.dempsey.common.core.domain.AjaxResult;
import com.dempsey.common.core.domain.R;
import com.dempsey.common.redis.constant.GoodCache;
import com.dempsey.common.redis.service.RedisService;
import com.dempsey.common.security.utils.SecurityUtils;
import com.dempsey.good.dao.Good;
import com.dempsey.good.dao.GoodBrand;
import com.dempsey.good.dao.GoodType;
import com.dempsey.good.mapper.GoodMapper;
import com.dempsey.good.service.GoodBrandService;
import com.dempsey.good.service.GoodService;
import com.dempsey.good.service.GoodTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * The type Goods controller.
 *
 * @author Dempsey  Date 2022/5/2 Description
 */
@RestController
@RequestMapping("/good")
public class GoodController {

    private final static Log log = LogFactory.get();

    @Autowired
    private RedisService redisService;

    @Autowired
    private GoodService goodService;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private GoodTypeService goodTypeService;

    @Autowired
    private GoodBrandService goodBrandService;

    @PostMapping("/createGood")
    public AjaxResult createGood(@RequestBody Good good) {
        log.info("请求参数: {}", good);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        good.setCreateUser(loginUser.getUser().getUserId());
        goodService.save(good);
        return AjaxResult.success();
    }

    @PostMapping("/updateGood")
    public AjaxResult updateGood(@RequestBody Good good) {
        log.info("请求参数: {}", good);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        good.setUpdateUser(loginUser.getUser().getUserId());
        goodService.updateById(good);
        return AjaxResult.success();
    }

    @PostMapping("/deleteGoodById")
    public AjaxResult deleteGoodById(@RequestParam int goodId) {
        log.info("请求参数: {}", goodId);
        goodService.removeById(goodId);
        return AjaxResult.success();
    }

    @PostMapping("/getGoodById")
    public AjaxResult getGoodById(@RequestParam int goodId) {
        AjaxResult ajax = AjaxResult.success();
        log.info("请求参数: {}", goodId);
        Good good = goodService.getById(goodId);
        ajax.put("good", good);

        String uuid = redisService.getCacheObject("seckill-acticity:" + goodId);
        ajax.put("seckillStr", uuid);

        return ajax;
    }

    @PostMapping("/getGoodByIdWithHeadImg")
    public AjaxResult getGoodByIdWithHeadImg(@RequestParam int goodId) {
        AjaxResult ajax = AjaxResult.success();
        log.info("请求参数: {}", goodId);
        Good good = goodService.getById(goodId);
        beCoveredImg(good);
        ajax.put("good", good);

        String uuid = redisService.getCacheObject("seckill-acticity:" + goodId);
        ajax.put("seckillStr", uuid);

        return ajax;
    }

    @PostMapping("/getGoodList")
    public AjaxResult getGoodList(@RequestParam int currentPage) {
        Page<Good> goodPage = new Page<>(currentPage, 10);
        List<Good> pageList = goodService.page(goodPage).getRecords();
        return AjaxResult.success(pageList);
    }

    @PostMapping("/getSelfGoodList")
    public AjaxResult getSelfGoodList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        QueryWrapper<Good> qw = new QueryWrapper<>();
        qw.eq("create_user", loginUser.getUser().getUserId());
        List<Good> goodList = goodService.list(qw);
        for (Good good : goodList) {
            beCoveredImg(good);
        }

        return AjaxResult.success(goodList);
    }

    @PostMapping("/getHome")
    public AjaxResult getHome() {
        AjaxResult ajax = AjaxResult.success();

        List<Good> swiperList = goodService.page(new Page<>(1, 3)).getRecords();
        List<Good> hotList = goodService.page(new Page<>(1, 20)).getRecords();;

        for (Good good : swiperList) {
            beCoveredImg(good);
        }
        for (Good good : hotList) {
            beCoveredImg(good);
        }

        ajax.put("swiperList", swiperList);
        ajax.put("hotList", hotList);

        return ajax;
    }

    private void beCoveredImg(Good good) {
        if (null == good.getPictures() || "".equals(good.getPictures())) {
            return;
        }
        String headPic = good.getPictures().split(",")[0];
        good.setPictures(headPic);
    }

    @PostMapping("/search")
    public AjaxResult search(@RequestParam String keyword, @RequestParam String searchType) {
        log.info("请求参数: {}", keyword, searchType);
        List<Good> goodList;
        switch (searchType) {
            case "name":
                goodList = goodService.getGoodByName(keyword);
                break;
            case "type":
                goodList = goodService.getGoodByType(keyword);
                break;
            case "brand":
                goodList = goodService.getGoodByBrand(keyword);
                break;
            default:
                return AjaxResult.error("不支持的搜索类型");
        }
        for (Good good : goodList) {
            beCoveredImg(good);
        }
        return AjaxResult.success(goodList);
    }

    @PostMapping("/searchGoodByName")
    public AjaxResult searchGoodByName(@RequestParam String goodName) {
        log.info("请求参数: {}", goodName);

        List<Good> goodList = goodService.getGoodByName(goodName);

        return AjaxResult.success(goodList);
    }

    @PostMapping("/searchGoodByType")
    public AjaxResult searchGoodByType(@RequestParam String goodType) {
        log.info("请求参数: {}", goodType);

        List<Good> goodList = goodService.getGoodByType(goodType);

        return AjaxResult.success(goodList);
    }

    @PostMapping("/searchGoodByBrand")
    public AjaxResult searchGoodByBrand(@RequestParam String goodBrand) {
        log.info("请求参数: {}", goodBrand);

        List<Good> goodList = goodService.getGoodByBrand(goodBrand);

        return AjaxResult.success(goodList);
    }

    @PostMapping("/createType")
    public AjaxResult createType(@RequestBody GoodType goodType) {
        log.info("请求参数: {}", goodType);
        goodTypeService.save(goodType);
        return AjaxResult.success();
    }

    @PostMapping("/getTypeById")
    public AjaxResult getTypeById(@RequestParam int goodTypeId) {
        log.info("请求参数: {}", goodTypeId);
        GoodType goodType = goodTypeService.getById(goodTypeId);
        return AjaxResult.success(goodType);
    }

    @PostMapping("/createBrand")
    public AjaxResult createBrand(@RequestBody GoodBrand goodBrand) {
        log.info("请求参数: {}", goodBrand);
        goodBrandService.save(goodBrand);
        return AjaxResult.success();
    }

    @PostMapping("/getBrandById")
    public AjaxResult getBrandById(@RequestParam int goodBrandId) {
        log.info("请求参数: {}", goodBrandId);
        GoodBrand goodBrand = goodBrandService.getById(goodBrandId);
        return AjaxResult.success(goodBrand);
    }

    @Cacheable(value = "goodStock", key = "#goodId")
    @PostMapping("/getStock")
    public R<Integer> getStock(@RequestParam("goodId") int goodId) {
        log.info("请求参数: {}", goodId);

        // 先去缓存拿
        Object cacheObject = redisService.getCacheObject(GoodCache.GOOD_KEY + goodId);
        Good good;
        if (cacheObject != null) {
            good = (Good) cacheObject;
        } else {
            // 拿不到去数据库查
            good = goodService.getById(goodId);
        }

        return R.ok(good.getStock());
    }

    @CacheEvict(value = "goodStock", key = "#goodId")
    @PostMapping("/delStock")
    public AjaxResult delStock(@RequestParam int goodId) {
        log.info("请求参数: {}", goodId);
        goodMapper.delStock(goodId);
        return AjaxResult.success();
    }
}
